package com.hse.virtualnetwork;

import com.hse.network.ICoordinatorClient;
import com.hse.network.exceptions.NetworkException;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.Arrays;

/**
 * Created by IntelliJ IDEA.
 * User: Lexa
 * Date: May 31, 2009
 * Time: 7:33:17 PM
 * To change this template use File | Settings | File Templates.
 */
public class VirtualCoordinatorClient implements ICoordinatorClient {
    private Socket sock;
    private byte[] recvBuffer;

    public VirtualCoordinatorClient(Socket socket) throws SocketException {
        this.sock = socket;
    }

    public void send(byte[] data) throws NetworkException {
        try {
            sock.getOutputStream().write(data);
        } catch (IOException e) {
            throw new NetworkException(e);
        }
    }

    public byte[] recv() throws NetworkException {
        if (recvBuffer != null)
            return recvBuffer;
        recvBuffer = null;
        try {
            byte[] data = new byte[1024];
            int recvSize = sock.getInputStream().read(data);
            return Arrays.copyOf(data, recvSize);
        } catch (IOException e) {
            throw new NetworkException(e);
        }
    }

    public boolean canRead() {
        try {
            byte[] data = new byte[1024];
            sock.setSoTimeout(1);
            int recvSize;
            try {
                recvSize = sock.getInputStream().read(data);
            } catch (SocketTimeoutException ex) {
                return false;
            }
            sock.setSoTimeout(0);
            if (recvSize == 0)
                return false;
            recvBuffer = Arrays.copyOf(data, recvSize);
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}
